package com.xiao.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiao.entity.UserEntity;
import com.xiao.service.UserService;
import com.xiao.util.XiaoUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("toMain")
	public String toMain() {
		return "main/main";
	}

	@RequestMapping("toUser")
	public String toUser() {
		return "user/user";
	}

	@RequestMapping("findAll")
	@ResponseBody
	public JSONObject findAll(UserEntity userEntity) {
		List<UserEntity> findAll = userService.findAllByPager(userEntity);
		int count = userService.findAllCount();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", findAll);
		jsonObject.put("total", count);
		return jsonObject;
	}

	@RequestMapping("delSome")
	@ResponseBody
	public int delSome(String ar) {
		int[] dels = XiaoUtils.getSplitString(ar);
		for (int i = 0; i < dels.length; i++) {
			// 循环删除
			if (dels[i] != 0) {
				userService.delOne(dels[i]);
			}
		}
		return 1;
	}

	@RequestMapping("toInsert")
	public String toInsert() {
		return "user/insert";
	}

	@RequestMapping("findOneByUname")
	@ResponseBody
	public int findOneByUname(String uname) {
		UserEntity userEntity = userService.findOneByUname(uname);
		if (userEntity != null) {
			return 1;
		} else {
			return 0;
		}
	}

	@RequestMapping("insert")
	@ResponseBody
	public int insert(UserEntity userEntity) {
		userService.insert(userEntity);
		return 1;

	}

	@RequestMapping("delOne")
	@ResponseBody
	public int delOne(int uid) {
		userService.delOne(uid);
		return 1;
	}

	@RequestMapping("toUpdate")
	public String toUpdate(int uid, Model model) {
		UserEntity userEntity = userService.findOneByUid(uid);
		model.addAttribute("ar", userEntity);
		return "user/update";
	}

	@RequestMapping("update")
	@ResponseBody
	public int update(UserEntity userEntity) {
		userService.update(userEntity);
		return 1;
	}

	@RequestMapping("findAllNoPager")
	@ResponseBody
	public List<UserEntity> findAllNoPager(){
		return userService.findAll();
	}
}
